package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.exception.PermissionException;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //使用分页插件(告诉mybatis 我要分页)
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //查询当前页面的数据
        List<Permission> permissions = permissionMapper.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), permissions);
    }

    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }

    @Override
    public Permission findById(Integer id) {
        return permissionMapper.findById(id);
    }

    @Override
    public void delete(Integer id) {
        //判断是否和角色-权限关系表存在引用关系，有引用关系就不能删除
        Integer count = permissionMapper.findCountById(id);
        if (count != null && count > 0) {
            //存在引用,不能删除
            throw new PermissionException("存在引用，不能删除");
        } else {
            //可以删除
            permissionMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void edit(Permission permission) {
        //查看是否重名，重名不能修改
        Integer count = permissionMapper.selectCountById(permission);
        if (count != null && count > 0) {
            //存在名字相同，不能修改
            throw new PermissionException("存在名字相同不能修改");
        } else {
            //可以修改
            permissionMapper.updateByPrimaryKey(permission);
        }


    }
}
